package others;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockTest {
    private static volatile int target;
    public static final Lock lock = new ReentrantLock();

    public static final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public static final Lock readLock = readWriteLock.readLock();
    public static final Lock writeLock = readWriteLock.writeLock();

    public static void write(Lock lock, int target) {
        try {
            lock.lock();
            ReadWriteLockTest.target = target;
            TimeUnit.SECONDS.sleep(1);
            System.out.println("write over");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static Integer read(Lock lock) {
        try {
            lock.lock();
            System.out.println("read over");
            TimeUnit.SECONDS.sleep(1);
            return target;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return -1;
    }

    public static void main(String[] args) {
//        Runnable readR = ()->read(lock);
//        Runnable writeR = ()->write(lock, 3);

        Runnable readR = ()->read(readLock);
        Runnable writeR = ()->write(writeLock, 3);
        for (int i = 0; i < 18; i++) {
            new Thread(readR).start();
        }
        for (int i = 0; i < 2; i++) {
            new Thread(writeR).start();
        }
    }
}
